<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-06-14
 * Time: 15:54
 */

namespace app\exam\controller;
use think\Controller;
use think\Loader;

//控制器基类
class Base extends Controller{
    private $file;       //图片地址
    public $width;      //图片长度
    public $height;     //图片长度
    private $type;        //图片类型
    private $img;       //原图的资源句柄
    private $new;       //新图的资源句柄
    //判断数据是否为空
    //@param $data(mix) 获取的数据
    public function isempty($data){
        if(!$data){
            return  self::res('10010','未发送任何数据');
        }else{
            return true;
        }
    }
    //返回判断数据的结果
    /*
    @param $code(int) 信息代码
    @param $msg(str) 返回信息
    @param $data(array) 返回的数据,可以为空
    */
    public function res($code,$msg,$data=''){
        if($data != ''){
            return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);
        }else{
            return json_encode(['code'=>$code,'msg'=>$msg]);
        }

    }
    //表单验证
    /*
     * @param $classname(str) model对应的名字
     * @param $data(array)      验证的数据
     * return str|''
     * */
    public  function  input_validate($classname,$data){
        $validate = Loader::validate($classname);
        if(!$validate->check($data)){
            return $validate->getError();
        }
    }
    //图片上传
    //@return str
    public function upimg(){
        $Img = controller('Img');
        //设置目录，与tp生成的目录一致。ceshi
        $timedir = date("Ymd");

        $files = request()->file("fileimg");
        if($files){
            $info = $files->move(ROOT_PATH . 'public' . DS . 'uploads/images');
            if($info){
                //图片绝对路径
                $img_url = $_SERVER ['HTTP_HOST'].Config('iMG_PATH').$timedir.'/'.$info->getFilename();
                //$this->thumb_start($img_url);
                // $this->image_center_crop(Config('iMG_PATH_BAK').$timedir.'/'.$info->getFilename(),'800','400',Config('iMG_PATH_BAK').$timedir.'/'.$info->getFilename());
                //返回图片的绝对路径
                return $img_url;
            }else{
                return false;
            }
        }else{
            return false;
        }

    }
    public  function image_center_crop($source, $width, $height, $target)
    {
        if (!file_exists($source)) return false;
        /* 根据类型载入图像 */
        switch (exif_imagetype($source)) {
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($source);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($source);
                break;
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($source);
                break;
        }
        if (!isset($image)) return false;
        /* 获取图像尺寸信息 */
        $target_w = $width;
        $target_h = $height;
        $source_w = imagesx($image);
        $source_h = imagesy($image);
        /* 计算裁剪宽度和高度 */
        $judge = (($source_w / $source_h) > ($target_w / $target_h));
        $resize_w = $judge ? ($source_w * $target_h) / $source_h : $target_w;
        $resize_h = !$judge ? ($source_h * $target_w) / $source_w : $target_h;
        $start_x = $judge ? ($resize_w - $target_w) / 2 : 0;
        $start_y = !$judge ? ($resize_h - $target_h) / 2 : 0;
        /* 绘制居中缩放图像 */
        $resize_img = imagecreatetruecolor($resize_w, $resize_h);
        imagecopyresampled($resize_img, $image, 0, 0, 0, 0, $resize_w, $resize_h, $source_w, $source_h);
        $target_img = imagecreatetruecolor($target_w, $target_h);
        imagecopy($target_img, $resize_img, 0, 0, $start_x, $start_y, $resize_w, $resize_h);
        /* 将图片保存至文件 */
        if (!file_exists(dirname($target))) mkdir(dirname($target), 0777, true);
        switch (exif_imagetype($source)) {
            case IMAGETYPE_JPEG:
                imagejpeg($target_img, $target);
                break;
            case IMAGETYPE_PNG:
                imagepng($target_img, $target);
                break;
            case IMAGETYPE_GIF:
                imagegif($target_img, $target);
                break;
        }
        return file_exists($target);
    }

    /**
     * 发送HTTP请求方法 获取到微信登陆需要用到的session_key
     * @param string $url  请求URL
     * @param array $params 请求参数
     * @param string $method 请求方法GET/POST
     * @return array $data  响应数据
     */
    public function curl_http($url, $params, $method = 'GET', $header = array(), $multi = false){
        $opts = array(
            CURLOPT_TIMEOUT    => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER   => $header
        );
        /* 根据请求类型设置特定参数 */
        switch(strtoupper($method)){
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('不支持的请求方式！');
        }
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        if($error) throw new Exception('请求发生错误：' . $error);
        return $data;
    }
    //三元运算符
    public function three($ifdata,$message_ok,$message_fail,$data=['0'=>''],$code_ok='10000',$code_fail='10001'){
        return $ifdata ? self::res($code_ok,$message_ok,$data):self::res($code_fail,$message_fail);
    }
    //构造方法，初始化
    public function thumb_start($_file) {
        $this->file = $_SERVER["DOCUMENT_ROOT"].'/'.$_file;
        list($this->width, $this->height, $this->type) = getimagesize($this->file);
        $this->img = $this->getFromImg($this->file, $this->type);

    }

    //cke专用图像处理
    public function ckeImg($new_width = 0,$new_height = 0) {
        list($_water_width,$_water_height,$_water_type) = getimagesize(MARK);
        $_water = $this->getFromImg(MARK,$_water_type);

        if (empty($new_width) && empty($new_height)) {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        if (!is_numeric($new_width) || !is_numeric($new_height)) {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        if ($this->width > $new_width) { //通过指定长度，获取等比例的高度
            $new_height = ($new_width / $this->width) * $this->height;
        } else {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        if ($this->height > $new_height) { //通过指定高度，获取等比例长度
            $new_width = ($new_height / $this->height) * $this->width;
        } else {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        $_water_x = $new_width - $_water_width - 5;
        $_water_y = $new_height - $_water_height - 5;


        $this->new = imagecreatetruecolor($new_width,$new_height);
        imagecopyresampled($this->new,$this->img,0,0,0,0,$new_width,$new_height,$this->width,$this->height);
        if ($new_width > $_water_width && $new_height > $_water_height) {
            imagecopy($this->new,$_water,$_water_x,$_water_y,0,0,$_water_width,$_water_height);
        }
        imagedestroy($_water);
    }

    //缩略图(固定长高容器，图像等比例，扩容填充，裁剪)[固定了大小，不失真，不变形]
    public function thumb($new_width = 0,$new_height = 0) {



        if (empty($new_width) && empty($new_height)) {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        if (!is_numeric($new_width) || !is_numeric($new_height)) {
            $new_width = $this->width;
            $new_height = $this->height;
        }

        //创建一个容器
        $_n_w = $new_width;
        $_n_h = $new_height;

        //创建裁剪点
        $_cut_width = 0;
        $_cut_height = 0;

        if ($this->width < $this->height) {
            $new_width = ($new_height / $this->height) * $this->width;
        } else {
            $new_height = ($new_width / $this->width) * $this->height;
        }




        if ($new_width < $_n_w) { //如果新高度小于新容器高度
            $r = $_n_w / $new_width; //按长度求出等比例因子
            $new_width *= $r; //扩展填充后的长度
            $new_height *= $r; //扩展填充后的高度
            $_cut_height = ($new_height - $_n_h) / 2; //求出裁剪点的高度
        }

        if ($new_height < $_n_h) { //如果新高度小于容器高度
            $r = $_n_h / $new_height; //按高度求出等比例因子
            $new_width *= $r; //扩展填充后的长度
            $new_height *= $r; //扩展填充后的高度
            $_cut_width = ($new_width - $_n_w) / 2; //求出裁剪点的长度
        }


        $this->new = imagecreatetruecolor($_n_w,$_n_h);
        imagecopyresampled($this->new,$this->img,0,0,$_cut_width,$_cut_height,$new_width,$new_height,$this->width,$this->height);
        $thumb=$this->_file;
        if(!is_dir($thumb)){
            mkdir($thumb);
        }
        switch ($this->type) {
            case 1:
                $data=imagegif($this->new,$thumb.time().'.gif',100);
                break;
            case 2:
                $data=imagejpeg($this->new,$thumb.time().'.jpg',100);
                break;
            case 3:
                $data=imagepng($this->new,$thumb.time().'.png',9);
                break;
            default:
                $data=imagepng($this->new,$thumb.time().'.png',9);
                break;
        }

        imagedestroy($this->img);
        imagedestroy($this->new);
        return $data;
    }

    //加载图片，各种类型，返回图片的资源句柄
    private function getFromImg($_file, $_type) {
        switch ($_type) {
            case 1 :
                $img = imagecreatefromgif($_file);
                break;
            case 2 :
                $img = imagecreatefromjpeg($_file);
                break;
            case 3 :
                $img = imagecreatefrompng($_file);
                break;
            // default:
            //  Tool::alertBack('警告：此图片类型本系统不支持！');
        }
        return $img;
    }


}